package com.gz.purchase.fragment;


import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gz.purchase.R;
import com.gz.purchase.adapter.PurcahseOrderAdapter;
import com.gz.purchase.app.Define;
import com.gz.purchase.event.EventCode;
import com.gz.purchase.event.MyEvent;
import com.gz.purchase.library.IAuthor;
import com.gz.purchase.library.IOrder;
import com.gz.purchase.library.listener.DeletePurchasePrderListener;
import com.gz.purchase.library.listener.GetPurchaseOrdersListener;
import com.gz.purchase.library.listener.RequestCode;
import com.gz.purchase.library.pojo.PurchaseOrderInfo;
import com.gz.purchase.library.pojo.UserInfo;
import com.gz.purchase.library.util.Constants;
import com.gz.purchase.library.util.CrashHandler;
import com.gz.purchase.library.util.PreferenceModel;
import com.gz.purchase.util.ToastUtils;
import com.gz.purchase.widget.DoubleDatePickerDialog;
import com.gz.purchase.widget.FooterView;
import com.gz.purchase.widget.LoadingCover;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import de.greenrobot.event.EventBus;


public class PurchaseFragment extends Fragment implements View.OnClickListener,PullToRefreshBase.OnRefreshListener, PurcahseOrderAdapter.DeleteOrderListener, LoadingCover.OnLoadingCoverRefreshListener, FooterView.OnFooterViewRefreshListener, DoubleDatePickerDialog.OnDateSetListener {
    private String TAG = PurchaseFragment.class.getSimpleName();
    private View mConvertView;
    private Context mContext;
    private PullToRefreshListView mPullListView;
    private LoadingCover mloadingCover;
    private FooterView mFooterView;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;
    private RelativeLayout rl_choice_for_time;
    private RelativeLayout rl_choice_for_order;
    private UserInfo info ;
    private Dialog mLoadingData;
    private DoubleDatePickerDialog timeDialog;
    private Calendar mCalendar;
    private MyGetPurchaseOrdersListener mPullListener;
    private MyGetPurchaseOrdersListener mScrollListener;
    private List<PurchaseOrderInfo> mDataList;
    private PurcahseOrderAdapter mAdapter;
    private int page = 1;
    private String startTime = null;
    private String endTime = null;
    private int orderType = -1;
    private PurchaseOrderInfo MydeleteOrder ;// 当前需要删除订单

    private MyDeletePurchasePrderListener myDeletePurchasePrderListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mConvertView == null) {
            mConvertView = inflater.inflate(R.layout.fragment_purchase, container, false);
            initView(inflater);
        }

        initlistener();
        initData();
        return mConvertView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ((ViewGroup)mConvertView.getParent()).removeView(mConvertView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPullListener.release();
        mScrollListener.release();
        myDeletePurchasePrderListener.release();
        EventBus.getDefault().unregister(this);
    }

    // 接收来自事件总线的事件
    public void onEvent(MyEvent event){
        if (event.getEventCode() == EventCode.REFRESH){
            onLoadingCoverRefresh();
        }

    }

    public void initView(LayoutInflater inflater){
        mContext =getActivity();
        info = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        tv_actionbar_title = (TextView) mConvertView.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) mConvertView.findViewById(R.id.tv_actionbar_deliveryName);
        rl_choice_for_time = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_time);
        rl_choice_for_order = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_order);

        mPullListView= (PullToRefreshListView) mConvertView.findViewById(R.id.list);
        mloadingCover = (LoadingCover) mConvertView.findViewById(R.id.layout_loading_cover);
        mFooterView = (FooterView) inflater.inflate(R.layout.footer_view, null);
        mPullListView.getRefreshableView().addFooterView(mFooterView);

        mLoadingData = new Dialog(mContext,R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);

        mCalendar = Calendar.getInstance();
        timeDialog = new DoubleDatePickerDialog(this.getActivity(),0,this,
                mCalendar.get(Calendar.YEAR),mCalendar.get(Calendar.MONTH),mCalendar.get(Calendar.DATE),true);
    }

    public void initlistener(){

        mPullListener = new MyGetPurchaseOrdersListener(RequestCode.PULL,this);
        mScrollListener = new MyGetPurchaseOrdersListener(RequestCode.SCROLL,this);
        myDeletePurchasePrderListener = new MyDeletePurchasePrderListener(this);
        rl_choice_for_time.setOnClickListener(this);
        rl_choice_for_order.setOnClickListener(this);
        mPullListView.setOnRefreshListener(this);
        mPullListView.setOnScrollListener(mFooterView);
        mloadingCover.setOnLoadingCoverRefreshListener(this);
        mFooterView.setOnFooterViewRefreshListener(this);

    }

    public void initData(){
        tv_actionbar_title.setText("代购订单");
        if (info != null){
            tv_actionbar_deliveryName.setText(info.getName()+":"+info.getUser_name());
        }
        mDataList = new ArrayList<PurchaseOrderInfo>();
        mAdapter =new PurcahseOrderAdapter(mContext,mDataList,this);
        mPullListView.setAdapter(mAdapter);

        onLoadingCoverRefresh();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_choice_for_time:
                timeDialog.show();
                break;
        }

    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        startTime = null;
        endTime = null;
        page = 1;
        IOrder.getInstance().getPurchaseOrders(page,startTime,endTime,orderType,mPullListener);
    }
    // 点击删除按钮的回调方法
    @Override
    public void onDelete(PurchaseOrderInfo deleteOrder) {
        if (deleteOrder != null){
            mLoadingData.show();
            MydeleteOrder = deleteOrder;
            IOrder.getInstance().deletePurchaseOrder(deleteOrder.getSsn(),myDeletePurchasePrderListener);

        }

    }

    @Override
    public void onLoadingCoverRefresh() {
        startTime = null;
        endTime = null;
        page = 1;
        IOrder.getInstance().getPurchaseOrders(page,startTime,endTime,orderType,mPullListener);

    }

    @Override
    public void onFooterViewRefresh() {
        page++;
        IOrder.getInstance().getPurchaseOrders(page,startTime,endTime,orderType,mScrollListener);

    }
    // 点击事件选择并选择起止时间后触发该方法
    @Override
    public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear, int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear, int endDayOfMonth) {
        startTime = String.format("%d-%d-%d",startYear,startMonthOfYear+1,startDayOfMonth);
        endTime = String.format("%d-%d-%d",endYear,endMonthOfYear+1,endDayOfMonth);
        CrashHandler.i(TAG, "开始时间=" + startTime + "结束时间=" + endTime);
        page = 1;
        mLoadingData.show();
        IOrder.getInstance().getPurchaseOrders(page,startTime,endTime,orderType,mPullListener);
    }

    /**
     *
     * 数据请求回调监听器
     *
     */
    private static class MyGetPurchaseOrdersListener extends  GetPurchaseOrdersListener{
        private PurchaseFragment mOuter;

        public MyGetPurchaseOrdersListener(RequestCode requestCode, PurchaseFragment mOuter) {
            super(requestCode);
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<PurchaseFragment>(mOuter);
        }

        @Override
        public void onResponseSuccess(List<PurchaseOrderInfo> purchaseOrderInfos) {
            if (purchaseOrderInfos == null){
               purchaseOrderInfos = new ArrayList<PurchaseOrderInfo>();
            }
            if (getRequestCode() == RequestCode.PULL){
                mOuter.mDataList.clear();
            }
            if (purchaseOrderInfos.size()< Define.LISTVIEW_ITEM_MIN_SIZE){
                mOuter.mFooterView.onRefreshComplete();
                mOuter.mPullListView.setOnScrollListener(null);
            }else{
                mOuter.mFooterView.onRefreshSuccess();
                mOuter.mPullListView.setOnScrollListener(mOuter.mFooterView);
            }
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            mOuter.mDataList.addAll(purchaseOrderInfos);
            mOuter.mAdapter.notifyDataSetChanged();
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.mloadingCover.onRefreshSuccess();

        }

        @Override
        public void onNoMoreData() {

            mOuter.mloadingCover.onRefreshFailed(Define.MSG_NOTHING);
            mOuter.mFooterView.onRefreshComplete();
            mOuter.mPullListView.setOnScrollListener(null);
            if (getRequestCode() == RequestCode.PULL){
                mOuter.mDataList.clear();
                mOuter.mAdapter.notifyDataSetChanged();
                ToastUtils.showToast(mOuter.getActivity(), "暂无内容");
            }
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }



        }

        @Override
        public void onNoNetWork() {
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()) {
                mOuter.mLoadingData.dismiss();
            }
            if (getRequestCode() == RequestCode.SCROLL){
                mOuter.page--;
            }
            mOuter.mFooterView.onRefreshFailed();
            mOuter.mloadingCover.onRefreshFailed(Define.MSG_LOADING_BY_CLICK);
            ToastUtils.showToast(mOuter.getActivity(), Define.MSG_TOAST_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mloadingCover.onRefreshFailed();
            mOuter.mFooterView.onRefreshFailed();
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            if (getRequestCode() == RequestCode.SCROLL){
                mOuter.page--;
            }
            ToastUtils.showToast(mOuter.getActivity(),Define.MSG_ON_RESPONSE_FAILED);

        }
    }

    /**
     * 删除订单回调监听器
     */
    public static class MyDeletePurchasePrderListener extends DeletePurchasePrderListener {
        private PurchaseFragment mOuter;

        public MyDeletePurchasePrderListener(PurchaseFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<PurchaseFragment>(mOuter);
        }

        @Override
        public void onThisOrderHasBeenInvalid() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.MydeleteOrder = null;
            ToastUtils.showToast(mOuter.getActivity(),"该订单已作废");

        }

        @Override
        public void onResponseSuccess() {
            mOuter.mDataList.remove(mOuter.MydeleteOrder);
            mOuter.mAdapter.notifyDataSetChanged();
            mOuter.MydeleteOrder = null;
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(),"删除成功");

        }

        @Override
        public void onNoNetWork() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(), Define.MSG_TOAST_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.MydeleteOrder = null;
            ToastUtils.showToast(mOuter.getActivity(),"删除失败");

        }
    }
}
